package com.sharp.portal.controller;

import com.sharp.kernel.config.response.Response;
import com.sharp.kernel.config.response.ResponseHandler;
import com.sharp.portal.constant.anno.PortalPage;
import com.sharp.portal.service.PortalManageService;
import com.sharp.portal.service.PortalQueryService;
import com.sharp.portal.vo.ConditionVO;
import org.springframework.boot.CommandLineRunner;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Title: PortalQueryCommonController
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2021/5/11 16:11
 */
public class PortalCommonController implements CommandLineRunner {
    @Resource
    protected PortalManageService portalManageService;
    @Resource
    protected PortalQueryService portalQueryService;

    @ApiIgnore
    @RequestMapping(value = "/condition", method = RequestMethod.GET)
    public ResponseEntity<Response<List<ConditionVO>>> getCondition(HttpServletRequest request) {
        List<ConditionVO> res = portalQueryService.getCondition(getCurrentUri(request));
        return ResponseHandler.generateResponse(res);
    }

    protected String getCurrentUri(HttpServletRequest request) {
        String uri = request.getRequestURI();
        int last = uri.indexOf("/", uri.indexOf("/", uri.indexOf("/") + 1) + 1);
        return uri.substring(0, last);
    }

    @Override
    public void run(String... args) {
        init();
    }

    public void init() {
        RequestMapping mappingArray = this.getClass().getAnnotation(RequestMapping.class);
        PortalPage portalPageAnno = this.getClass().getAnnotation(PortalPage.class);
        if (mappingArray != null) {
            String[] pathArray = mappingArray.value();
            if (pathArray.length != 0 && portalPageAnno != null) {
                if (!portalManageService.existed(pathArray[0])) {
                    portalManageService.addQuery(pathArray[0], portalPageAnno.value(), portalPageAnno.description(),
                            portalPageAnno.sqlDbName(), portalPageAnno.sqlTableName());
                }
            }
        }
    }
}
